package top.younote.cherry.selenium;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.younote.cherry.model.bo.WorldCupBO;
import top.younote.cherry.service.IMailService;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: duanyu
 * @CreateTime: 2022-11-24 22:33
 **/
@Slf4j
@Service
public class WorldCupService {
    private static WorldCupBO worldCup = null;
    @Value("${spring.mail.log.to}")
    private String to;

    @Autowired
    private BaiduService baiduService;
    @Autowired
    private IMailService iMailService;

    public void sendChange() {
        WorldCupBO curWorldCup = baiduService.getWorldCup();
        log.info("请求结果：{}", JSON.toJSONString(curWorldCup));
        StringBuilder builder = new StringBuilder();
        builder.append("<b>" + "已经结束比赛结果：" + "</b>").append("<br/>");
        if (worldCup == null) {
            worldCup = curWorldCup;
            List<String> result = worldCup.getFinishScheduleList().stream().map(this::build).collect(Collectors.toList());
            result.forEach(res -> builder.append(res).append("<br/>"));
//            iMailService.sendHtmlMail(to, "世界杯比赛结果", builder.toString());
            sendMessage(builder.toString());
        }
        if (curWorldCup.getFinishScheduleList().size() != worldCup.getFinishScheduleList().size()) {
            List<String> history = worldCup.getFinishScheduleList().stream()
                    .map(this::build).collect(Collectors.toList());
            List<String> curHistory = curWorldCup.getFinishScheduleList().stream()
                    .map(this::build).collect(Collectors.toList());
            if (history.size() != curHistory.size()) {
                Optional<String> first = curHistory.stream().filter(res -> !history.contains(res)).findFirst();
                first.ifPresent(this::sendMessage);
            }

        }
        worldCup = curWorldCup;
    }

    private String build(WorldCupBO.Base base) {
        return String.format("%s - %s %s : %s", base.getHome(), base.getAway(), base.getHomeScore(), base.getAwayScore());
    }

    private void sendMessage(String content){
        iMailService.sendHtmlMail(to, "世界杯比赛结果", content);
        iMailService.sendHtmlMail("xushihuilin@imdada.cn", "世界杯比赛结果", content);
    }
}
